
const express = require("express");
const router = express.Router();
const path = require("path");
const pool = require("../pool.js");
const utils = require("../utils/index.js");
const moment = require("moment-timezone");
const multer = require("multer");
const fs = require("fs");
const crypto = require("crypto");
const CryptoJS = require("crypto-js");
const FormData = require("form-data");
const axios = require("axios");
const nodemailer = require('nodemailer');
const secrtKey = "zhijian No1.";
const jwt = require("jsonwebtoken");
const expressJWT = require("express-jwt");
//定义一个验证token的中间件
const verifyToken = (req, res, next) => {
    let token = req.headers.authorization;
    // Check if token exists
    if (!token) {
        return res.status(403).send("Authentication requires a token");
    }
    try {
        // Remove Bearer from string
        token = token.replace(/^Bearer\s+/, "");
        // Verify token
        const decoded = jwt.verify(token, secrtKey);
        // Check if user id in token is same as in request to change password
        if (req.body.uid != decoded.uid) {
            return res.status(401).send("Unauthorized: Token does not match user ID");
        }
        // Add user from payload
        req.user = decoded;
    } catch (err) {
        return res.status(401).send("Invalid token");
    }
    return next();
};

const transporter = nodemailer.createTransport({
    host: 'smtp.163.com',
    port: 465,
    secure: true,
    auth: {
        user: 'liudaoyuan008@163.com',
        pass: 'ICIFALJCQDOPOPJL'
    }
});

//发送验证码
router.post('/sendCode', async (req, res) => {

    const { email } = req.body;
    //先验证库里有没有被注册过 
    let sql = `select * from porter_user where email = ?`

    let emailResult = await mysqlHandel(sql, [email]);
    if (emailResult.length>0) return res.send({ code: 1, msg: 'Email has been registered' })
    // 生成验证码
    const verificationCode = Math.floor(100000 + Math.random() * 900000).toString();

    const mailOptions = {
        from: 'liudaoyuan008@163.com',
        to: email,
        subject: 'Verification Code',
        text: `Your verification code is: ${verificationCode}`
    };
    transporter.sendMail(mailOptions, async (error, info) => {
        if (error) {
            console.error('Error sending email:', error); // 输出详细错误信息
            return res.status(500).send('Error sending email');
        }
        // 在这里将验证码存储到数据库
        let sqlPending = `select * from pending_users where email = ?`
        let pendingResult = await mysqlHandel(sqlPending, [email]);
        if (pendingResult.length>0) {
            //更新
            let updatesql = `UPDATE pending_users SET code = ? where id = ?`
            let a= await mysqlHandel(updatesql, [verificationCode, pendingResult[0].id]);
        } else {
            let obj = {}
            obj.id = utils.createId();
            obj.email = email;
            obj.code = verificationCode;
            const { text, values } = utils.createInsertSql(
                "pending_users",
                obj
            );

            let result = await utils.query(text, values);
        }


        res.send({code:0,msg:'success'});

    });
})

//验证码登录  
router.post('/loginByCode', async (req, res) => {
    const { email, verificationCode } = req.body;
    //1.获取用户传的账号密码 与 库里数据比对
    let sqlStr = `select * from pending_users where email = ? and code = ?`;
    let result = await mysqlHandel(sqlStr, [email, verificationCode]);
    if (result.length == 0) return res.send({ code: 1, msg: 'Incorrect email address or verificationCode' })
    let sqlStr1 = `select * from porter_user where email = ?`
    let result1 = await mysqlHandel(sqlStr1, [email]);
    let token = jwt.sign({ uid: result1[0].id }, secrtKey);
    res.send({
        code: 0,
        msg: "success",
        token: token,
        uid: result1[0].id,
        email: result1[0].email
    });
})


//注册接口
router.post("/register", async (req, res) => {
    const { email,verificationCode,password,nickname } = req.body;

    if (!email || !verificationCode || !password)
        return res.send({
            result: 1,
            msg: "Parameter cannot be empty",
        });
    // console.log(jwt.sign({ id: 1 }, secrtKey));
    //1.先获取用户传过来的账号密码,库里查询是否用户名重复 （格式是否正确）  不正确就抛给客户端
    let sqlStr = `SELECT * FROM pending_users WHERE email = ? AND code = ?`;
    let result = await mysqlHandel(sqlStr, [email, verificationCode]);
    if (result.length == 0) return res.send({ code: 1, msg: 'Incorrect email address or verification code' })
    //在查是否注册过
    let sql = `select * from porter_user where email = ?`

    let emailResult = await mysqlHandel(sql, [email]);
    if (emailResult.length > 0) return res.send({ code: 1, msg: 'Email has been registered' })
    //开始注册 写入数据
    let obj = {}
    obj.id = utils.createId();
    obj.email = email;
    obj.nickname = nickname;
    obj.password = password;
    obj.create_date = utils.formatDate(new Date());
    obj.update_date = utils.formatDate(new Date());
    const { text, values } = utils.createInsertSql(
        "porter_user",
        obj
    );
    let resultUser = await utils.query(text, values);
    res.send({code:0,msg:'success'});
 
});
//登录接口
router.post("/login",async (req, res) => {
    const { email, password } = req.body;
    //1.获取用户传的账号密码 与 库里数据比对
    let sqlStr = `select * from porter_user where email = ? and password = ?`;
    let result = await mysqlHandel(sqlStr, [email, password]);
    if (result.length==0) return res.send({ code: 1, msg:'Incorrect email address or password'})
    let token = jwt.sign({ uid: result[0].id }, secrtKey);
    res.send({
        code: 0,
        msg: "success",
        token: token,
        uid: result[0].id,
        email: result[0].email

    });    
});

// 修改密码
router.post("/editUserInfo", async (req, res) => {
    //1. 获取用户传的账号密码和新密码 与库里比对 匹配成功后 更新密码
    //比对信息
    const { verificationCode, email, newPassword } = req.body
    let sqlStr = `select * from pending_users where email = ? and code = ?`;
    let result = await mysqlHandel(sqlStr, [email, verificationCode]);
    if (result.length == 0) return res.send({ code: 1, msg: 'Incorrect email address or verificationCode' })
    //验证码正确 去修改密码
    let sql = `update porter_user set password = ? where email=? `    
    let result1 = await mysqlHandel(sql, [newPassword, email]);
    res.send({code:0,msg:'success'})



     

     
});
async function mysqlHandel(sql, data) {
    return new Promise((resolve, reject) => {
        pool.query(sql, data, (error, results, fields) => {
            console.log(error)
            if (error) {
                return reject(error);
            }
            resolve(results);
        });
    });
}
module.exports = router;